package com.smart.manager.weixin.mp.handler;

import com.smart.common.exception.SmartException;
import com.smart.wap.bodys.WxmpBody;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.service.WxOAuth2Service;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class WxmpHandler {

    private final WxMpService wxMpService;


    public WxOAuth2UserInfo getMpUserInfo(String appId, String code) {
        try {
            log.warn("换accesstoken的code = {}" ,code);
            WxMpService mpService = wxMpService.switchoverTo(appId);

                    log.warn( mpService.getWxMpConfigStorage());
            WxOAuth2Service oAuth2Service = mpService.getOAuth2Service();
            WxOAuth2AccessToken accessToken =oAuth2Service.getAccessToken(code);
            return mpService.getOAuth2Service().getUserInfo(accessToken, "zh_CN");
        } catch (WxErrorException e) {

            throw new SmartException("获取用户OPENID数据失败:" + e.getMessage());
        }
    }

    public WxJsapiSignature getPageTicket(WxmpBody.TicketBody body) {
        try {


            return wxMpService.switchoverTo(body.getAppId()).createJsapiSignature(body.getUrl());
        } catch (Exception e) {
            throw new SmartException("获取网页签名失败:" + e.getMessage());
        }


    }
}
